package cx.hoffmann.bab.dao;

import cx.hoffmann.bab.model.User;
import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

/**
 * Created by IntelliJ IDEA.
 * User: lasombra
 * Date: 2009/11/05
 * Time: 8:25:50 PM
 */
public class UserDAO
{
	private EntityManager em = null;
	private Logger log = Logger.getLogger( this.getClass() );

	public Boolean insert( User user )
	{
		try
		{
			em = PersistenceInitializer.getEntityManager();
			em.getTransaction().begin();

			log.debug( "Inserting user " + user );
			em.persist( user );

			em.getTransaction().commit();

			return true;
		}
		catch( ConstraintViolationException cvex )
		{
			log.error( "Error inserting user: " + user );
			log.error( "Possible cause: Duplicate e-mail." );
		}
		catch( PersistenceException pex )
		{
			log.error( "Error inserting user: " + user.getFirstName() + " " + user.getLastName() );
			String fullMessage = pex.getMessage();

			// Tries to split the property name from the exception message
			// 1st we look if the message starts with " not-null"
			if( fullMessage.split( ":" )[ 1 ].startsWith( " not-null" ) )
			{
				// If so, split the hell of the fullMessage to get the property's name
				String property = fullMessage.split( ":" )[ 2 ].split( "\\." )[ 5 ];
				log.error( property );
				log.error( "Property " + property + " can't be null" );
			}
		}
		catch( Exception ex )
		{
			log.error( "Error inserting user: " + user );
			log.error( ex );
			return false;
		}
		finally
		{
			em.close();
		}

		return false;
	}

	public User findByEmail( String email )
	{
		User foundUser;
		String queryString = "FROM User u WHERE u.email = ?";

		try
		{
			em = PersistenceInitializer.getEntityManager();

			Query query = em.createQuery( queryString );
			query.setParameter( 1, email );
			foundUser = ( User ) query.getSingleResult();

			if( foundUser != null )
			{
				log.debug( "User " + foundUser + " found!" );
				return foundUser;
			}
			else
			{
				return null;
			}
		}
		catch( Exception ex )
		{
			log.error( "Error looking for email " + email );
			log.error( ex );
		}
		finally
		{
			em.close();
		}

		return null;
	}

	public Boolean delete( User user )
	{
		User userToBeDeleted = this.findByEmail( user.getEmail() );

		try
		{
			em = PersistenceInitializer.getEntityManager();
			em.getTransaction().begin();

			log.debug( "Removing user " + user );
			userToBeDeleted = em.merge( userToBeDeleted );
			em.remove( userToBeDeleted );

			em.getTransaction().commit();

			return true;
		}
		catch( Exception ex )
		{
			log.error( "Error removing user " + user );
			log.error( ex );
			return false;
		}
		finally
		{
			em.close();
		}
	}
}